import React, {PureComponent} from "react";
import {Tabs, BackTop, Button, message} from 'antd';
import {connect} from "react-redux";
import {actionCreators} from "../store";
import '../style.css'

const TabPane = Tabs.TabPane;

class ContentListComponent extends PureComponent {

    constructor(props) {
        super(props);
        this.isComponentWillUnMount = false;
        this.newTabIndex = 0;
        const panes = [
            {title: '集群设备', key: 'tab_1', closable: false}
        ];
        this.state = {
            panes,
            activeKey: panes[0].key,
        };
    }

    componentWillUnmount() {
        this.isComponentWillUnMount = true;
        clearTimeout(this.interval);
    }

    componentDidMount() {
        this.props.loadDevicesList();
        this.props.connectionWS(img => {
            if (!this.isComponentWillUnMount) {
                this.forceUpdate();
            }
        });
        this.props.connectionExecCurrWS();
        this.props.connectionExecHealthWS();
    }

    onChangeTabs = (activeKey) => {
        this.setState({activeKey});
    };

    onEditTabs = (targetKey, action) => {
        this[action](targetKey);
    };

    add = (id, content) => {
        const panes = this.state.panes;
        const activeKey = `newTab_${this.newTabIndex++}`;
        panes.push({title: `设备[${id}]-${this.newTabIndex}`, content: content, key: activeKey});
        this.setState({panes, activeKey});
    };

    remove = (targetKey) => {
        let activeKey = this.state.activeKey;
        let lastIndex = -1;
        this.state.panes.forEach((pane, i) => {
            if (pane.key === targetKey) {
                lastIndex = i - 1;
            }
        });
        const panes = this.state.panes.filter(pane => pane.key !== targetKey);
        if (panes.length && activeKey === targetKey) {
            if (lastIndex >= 0) {
                activeKey = panes[lastIndex].key;
                if (lastIndex === 0) {
                    //还原索引
                    this.newTabIndex = 0;
                }
            } else {
                activeKey = panes[0].key;
            }
        }
        this.setState({panes, activeKey});
    };

    devicesBtnStartClick = (e, script, device) => {
        e.stopPropagation();
        console.log(script, device);
        let json = {
            script,
            device
        };
        this.props.loadRYMSingleReStart(json, (msg) => {
            message.success(msg);
        });
    };

    devicesBtnStopClick = (e, script, device) => {
        e.stopPropagation();
        console.log(script, device);
        let json = {
            script,
            device
        };
        this.props.loadRYMSingleStop(json, (msg) => {
            message.success(msg);
        });
    };

    allDevicesBtnStartClick = e => {
        this.props.loadRYMStart(msg => {
            message.success(msg);
        });
    };

    allDevicesBtnStopClick = e => {
        this.props.loadRYMStop(msg => {
            message.success(msg);
        });
    };

    render() {
        const {devicesList, home, currentAppInfo, execHealthInfo} = this.props;
        return (
            <React.Fragment>
                <BackTop/>
                <div className={'all-control-content'}>
                    <Button onClick={this.allDevicesBtnStartClick} type="primary">重启所有脚本</Button>
                    <div style={{width: 30}}/>
                    <Button onClick={this.allDevicesBtnStopClick} type="danger">关闭所有脚本</Button>
                    <div style={{width: 30}}/>
                </div>
                <Tabs
                    onChange={this.onChangeTabs}
                    activeKey={this.state.activeKey}
                    type="editable-card"
                    onEdit={this.onEditTabs}
                >
                    {this.state.panes.map((pane) => {
                        if (pane.key === 'tab_1') {
                            return <TabPane tab={pane.title} key={pane.key} closable={pane.closable}>
                                <div className={'devices-content'}>
                                    {home != null && devicesList != null && devicesList.map((item, index) => {
                                        let list = home[`rym_${item}`];
                                        if (list != null && list.length > 0) {
                                            let health = 0;
                                            execHealthInfo.forEach((value) => {
                                                if (value.device === item && value.health === 1) {
                                                    health = 1;
                                                }
                                            });
                                            return (<div key={index} className={'device-item'}
                                                         onClick={() => this.add(item, item)}>
                                                <span
                                                    className={`device-item-span ${health === 1 ? 'device-item-span-health' : 'device-item-span-no-health'}`}>设备{health === 1 ? '健康' : '不健康'}:{item}</span>
                                                <div className={'device-item-img'}
                                                     style={{backgroundImage: "url(http://0.0.0.0:9990/" + list[0] + ")"}}
                                                />
                                                <div className={'devices-btn-content'}>
                                                    <Button type="primary"
                                                            onClick={e => this.devicesBtnStartClick(e, currentAppInfo.script, item)}>重启脚本</Button>
                                                    <Button type="danger"
                                                            onClick={e => this.devicesBtnStopClick(e, currentAppInfo.script, item)}>停止脚本</Button>
                                                </div>
                                            </div>)
                                        }
                                        return null;
                                    })}
                                </div>
                            </TabPane>
                        } else {
                            return <TabPane tab={pane.title} key={pane.key} closable={pane.closable}>
                                <div className={'devices-content'}>
                                    {home != null && home[`rym_${pane.content}`] != null && home[`rym_${pane.content}`].map((item, index) => {
                                        return (<div key={item} className={'device-item-dir-img'}>
                                            <div className={'device-item-img'}
                                                 style={{backgroundImage: "url(http://0.0.0.0:9990/" + item + ")"}}
                                            />
                                        </div>)
                                    })}
                                </div>
                            </TabPane>
                        }
                    })}
                </Tabs>
            </React.Fragment>
        );
    }
}

const mapState = (state, ownProps) => ({
    home: state.getIn(['home']),
    devicesList: state.getIn(['home', 'devicesList']),
    currentAppInfo: state.getIn(['home', 'currentAppInfo']),
    execHealthInfo: state.getIn(['home', 'execHealthInfo']),
});

const mapDispatch = (dispatch) => ({
    loadDevicesList() {
        dispatch(actionCreators.loadDevicesList())
    },
    connectionWS(func) {
        actionCreators.connectionWS(dispatch, func)
    },
    connectionExecCurrWS(func) {
        actionCreators.connectionExecCurrWS(dispatch, func)
    },
    connectionExecHealthWS(func) {
        actionCreators.connectionExecHealthWS(dispatch, func)
    },
    loadRYMSingleReStart(json, func) {
        dispatch(actionCreators.loadRYMSingleReStart(json, func))
    },
    loadRYMSingleStop(json, func) {
        dispatch(actionCreators.loadRYMSingleStop(json, func))
    },
    loadRYMStart(func) {
        dispatch(actionCreators.loadRYMStart(func))
    },
    loadRYMStop(func) {
        dispatch(actionCreators.loadRYMStop(func))
    }
});

export default connect(mapState, mapDispatch)(ContentListComponent);
